package com.lishe.lishe.lishe.module.commonclass;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.activity.MineWelfareActivity;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.module.mall.activity.MallGoodsActivity;
import com.lishe.lishe.lishe.module.mall.fragment.GoodsDetailFragent;
import com.lishe.lishe.lishe.module.mall.fragment.MallFragemtn;

/**
 * Created by shino on 2017/10/18.
 * 网页专用activity
 */

public class WebActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout titleLayout;
    private TextView title;
    private Button callBack;
    private WebView myWebView = null;
    private boolean isRequesting = false;
    private String url;
    public final static int FILECHOOSER_RESULTCODE = 1001;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 1002;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private ProgressBar progress;
    WebSettings webSettings;
    private JSMethod jsMethod;
    private boolean isGetOut = false;//是否直接退出webview
    private boolean isGetOutToMain = false;//是否直接退出webview，跳到指定页
    private boolean isGetOutToWealfareList = false;//是否直接退出webview，跳到指定页

    public static void jump(Activity activity, String url) {
        Intent intent = new Intent(activity, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("isGetOutToMain", false);
        activity.startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_webview);
        url = getIntent().getStringExtra("url");
        Uri uri = this.getIntent().getData();
        title = findViewById(R.id.title_text_title);
        title.setText("福利领取");
        isGetOutToMain = getIntent().getBooleanExtra("isGetOutToMain", false);
        if (url == null) {//从短信进来
//            StringBuilder sb = new StringBuilder();
//            // 唤起链接
//            sb.append("string : ").append(getIntent().getDataString()).append("\n");
//            sb.append("scheme : ").append(uri.getScheme()).append("\n");
//            sb.append("host : ").append(uri.getHost()).append("\n");
//            sb.append("port : ").append(uri.getPort()).append("\n");
//            sb.append("path : ").append(uri.getPath()).append("\n");
//            // 接收唤起的参数
//            sb.append("name : ").append(uri.getQueryParameter("name")).append("\n");
//            sb.append("page : ").append(uri.getQueryParameter("page"));
//            if(getIntent().getDataString()!=null){
//                isGetOutToMain = true;
//            }
            isGetOutToWealfareList = true;
            url = getIntent().getDataString().replace("lishe168://", "") + "&token=" + Globals.getToken() + "&source=Android";
            title.setText("福利领取");
            title.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(Globals.getToken())) {//去登录
                doCheckLoginIfNeedAndRedirectAuth(WebActivity.this);
            }
        } else {
            if (url.contains("?SN=") || url.contains("/z/")) {//去登录
                isGetOutToWealfareList = true;
                title.setText("福利领取");
                title.setVisibility(View.VISIBLE);
                url = url + "&token=" + Globals.getToken() + "&source=Android";
                if (TextUtils.isEmpty(Globals.getToken())) {
                    doCheckLoginIfNeedAndRedirectAuth(WebActivity.this);
                }
            }
        }
        if (url != null) {
            Log.e("webactivity--url--", url);
        }
        initView();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void initView() {
        progress = findViewById(R.id.progress);
        myWebView = findViewById(R.id.webView);
        titleLayout = findViewById(R.id.title_relativelayout);
        callBack = findViewById(R.id.title_left_button);
        callBack.setOnClickListener(this);
        if (url.contains("?SN=") || url.contains("/z/")) {//titleLayout针对福利领取使用
            titleLayout.setVisibility(View.VISIBLE);
        } else {
            titleLayout.setVisibility(View.GONE);
        }
        webSettings = myWebView.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);


        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        myWebView.clearCache(true);
        //设置自适应屏幕，两者合用
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //适配屏幕
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(true); //隐藏原生的缩放控件
        webSettings.setDefaultFontSize(15);//默认字体大小
//        DisplayMetrics metrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics);
//        int mDensity = metrics.densityDpi;
//        if (mDensity == 120) {
//            webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
//        } else if (mDensity == 160) {
//            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
//        } else if (mDensity == 240) {
//            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
//        }
        //支持自动播放音乐
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.setWebChromeClient(new MyWebChromeClient());
        isRequesting = true;
        myWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {  //表示按返回键
                        myWebView.goBack();   //后退
                        //webview.goForward();//前进
                        return true;    //已处理
                    }
                }
                return false;
            }
        });
        progress.setVisibility(View.GONE);
//        myWebView.setVisibility(View.INVISIBLE);
        myWebView.loadUrl(url);

        jsMethod = new JSMethod();
        myWebView.addJavascriptInterface(jsMethod, "doApp");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                if (isGetOutToMain) {

                    finish();
                    Intent intent = new Intent(WebActivity.this, MainActivity0.class);
                    startActivity(intent);
                } else if (isGetOutToWealfareList) {
                    finish();
                    MineWelfareActivity.jump(WebActivity.this);
                } else {
                    if (isGetOut) {
                        finish();
                    } else {
                        if (myWebView.canGoBack()) {
                            myWebView.goBack();
                        } else {
                            super.onBackPressed();
                        }
                    }
                }
//                if (isGetOut) {
//                    finish();
//                } else {
//                    if (myWebView.canGoBack()) {
//                        myWebView.goBack();
//                    } else {
//                        super.onBackPressed();
//                    }
//                }
                break;
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {//url拦截事件
//            myWebView.setVisibility(View.INVISIBLE);
//            progress.setVisibility(View.VISIBLE);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
//            progress.setVisibility(View.GONE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            imgReset();
//            myWebView.setVisibility(View.VISIBLE);
//            progress.setVisibility(View.GONE);
        }
    }

    boolean isOnPause = false;

    @Override
    public void onPause() {
        myWebView.onPause();

        super.onPause();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        myWebView.onResume();
        super.onResume();

    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
//        myWebView.setVisibility(View.GONE);
    }

    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        myWebView.destroy();
        super.onDestroy();
    }

    private class MyWebChromeClient<FileChooserParams> extends WebChromeClient {

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android 3.0+ 文件选择
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.4 为了支持安卓5.0和6.0等高版本系统
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(filePathCallback);
            return true;
        }
    }

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"),
                FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadCallbackAboveL = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        startActivityForResult(chooserIntent,
                FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }


    @Override
    public void onBackPressed() {
        if (isGetOutToMain) {
            finish();
            Intent intent = new Intent(WebActivity.this, MainActivity0.class);
            startActivity(intent);
        } else if (isGetOutToWealfareList) {
            finish();
            MineWelfareActivity.jump(WebActivity.this);
        } else {
            if (isGetOut) {
                finish();
            } else {
                if (myWebView.canGoBack()) {
                    myWebView.goBack();
                } else {
                    super.onBackPressed();
                }
            }
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
//            myWebView.goBack();// 返回前一个页面
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri result = (data == null || resultCode != RESULT_OK) ? null : data
                .getData();
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadCallbackAboveL)
                return;
            if (result != null) {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
            } else {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
            }
            mUploadCallbackAboveL = null;
            // onActivityResultAboveL(requestCode, resultCode, data);
        }
    }

    /**
     * H5点击监听
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void listenerJsOnclik() {
        myWebView.evaluateJavascript("value()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Log.e("点击监听", "onReceiveValue value=" + s);
            }
        });
    }

    class JSMethod {
        /**
         * 前端使用的android函数
         *
         * @param type 0、默认，1、商品详情，2、加入购物车，3、积分领取,4、可以结束（jsonString=false不是立即结束，true为立即结束）
         */
        @JavascriptInterface
        public void doApp(int type, String jsonString) {
//            if(jsonString==null){
//                jsonString="没有值";
//            }
//            Log.e("Webview_doApp()",type+"--"+jsonString);
//            toast("H5调用app-type="+type+"str-"+jsonString);
            switch (type) {
                case 0:
                    normnalMethod(jsonString);
                    break;
                case 1:
                    getGoodsMethod(jsonString);
                    break;
                case 2:
                    addToGoodsCarMethod(jsonString);
                    break;
                case 3:
                    getIntegralMethod(jsonString);
                    break;
                case 4:
                    finishWeb(jsonString);
                    break;
            }
        }

        /**
         * 默认方法
         *
         * @param jsonString
         */
        public void normnalMethod(String jsonString) {
            Log.e("normnalMethodH5交互", jsonString);
        }

        /**
         * 商品详情
         *
         * @param jsonString
         */
        public void getGoodsMethod(String jsonString) {
            Log.e("getGoodsMethodH5交互", jsonString);
            MallGoodsActivity.jump(WebActivity.this, jsonString);
        }

        /**
         * 添加到购物车
         *
         * @param jsonString
         */
        public void addToGoodsCarMethod(String jsonString) {
            Log.e("addToGoodsCarMethodH5交互", jsonString);
        }

        /**
         * 积分领取
         *
         * @param jsonString
         */
        public void getIntegralMethod(String jsonString) {
            finish();
            Intent intent = new Intent(WebActivity.this, MainActivity0.class);
            startActivity(intent);
        }

        /**
         * 可结束操作
         *
         * @param jsonString
         */
        public void finishWeb(String jsonString) {
            Log.e("web结束这个页面", jsonString);
            if (jsonString.equals("false")) {
                isGetOut = true;
            } else if (jsonString.trim().equals("true")) {
                Log.e("关闭", "finish");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        if (isGetOutToMain) {
                            MainActivity0.jump(WebActivity.this);
                        }
                        if (isGetOutToWealfareList) {
                            MineWelfareActivity.jump(WebActivity.this);
                        }
                    }
                });

            }

        }
    }
    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     * http://blog.csdn.net/smileiam/article/details/72123227,资料来源
     **/
    private void imgReset() {
        myWebView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                "}" +
                "})()");
    }}
